package com.cjw.campus.core.utils;

import cn.hutool.core.io.FileUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class UploadUtil {

    /**
     * 单文件上传
     * @param file
     * @return
     */
    public static String uploadFile (MultipartFile file) {
//        定义上传路径
        try {
            // 获取文件的名称
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀名 例如：.png
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // uuid 生成文件名
            String uuid = String.valueOf(UUID.randomUUID());
            String fileName = uuid + fileSuffix;
            String folder = "D:\\upload" + File.separator;
            if (!FileUtil.exist(folder)) {
                FileUtil.mkdir(folder);
            }
            String path = folder + fileName;
            File file1 = FileUtil.writeBytes(file.getBytes(), path);
            if (file1.length() > 0) {
                return fileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 多文件上传
     * @param files
     * @return
     */
    public static List<String> uploadFiles (MultipartFile[] files) {
        List<String> paths = new ArrayList<>();
        for (MultipartFile file : files) {
            String path = uploadFile(file);
            paths.add(path);
        }
        return paths;
    }

}
